package battleship;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;

public class NewGameServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // wait for somebody to join your game
        System.out.println("NewGameServlet get: starting");
    	String userToken= request.getParameter("token");
    	int id= (Integer) UserIdTokenHashMap.idTokenMap.get(userToken);
      //  int id = Integer.parseInt(request.getParameter("id"));
        User user = Context.users[id];
//        Game game = user.game;

        User opp;
        try {
            opp = user.waitForJoin.take();
            //opp = user.waitForJoin.poll(1000, TimeUnit.MILLISECONDS);
            if (!user.waitingForOpponent) {
                return;
            }

            response.setContentType("text/plain");
            PrintWriter out = response.getWriter();

//            if (opp == null) {
//                out.print("{\"username\":\"\"}"); // return an empty string as the username
//                out.close();
//                return;
//            }

//            String startingPlayer = user.startingPlayer ? "true" : "false";
            out.print("{\"username\":\"" + opp.getUsername() + "\"}");
            out.close();
        } catch (InterruptedException e) {
            System.out.println("InterruptedException: " + e.getMessage());
        }
        System.out.println("NewGameServlet get: finished");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // open a new game
        System.out.println("NewGameServlet post: starting");

        String userToken= request.getParameter("token");
    	int id= (Integer) UserIdTokenHashMap.idTokenMap.get(userToken);
        // get the user's ID
      //  int id = Integer.parseInt(request.getParameter("id"));
        User user = Context.users[id];

        // start a new game
        Game newGame = new Game();
        newGame.player1ID = id;
        user.game = newGame;
        user.waitingForOpponent = true;

        // add the new game to the global open games list
        Context.openGames.add(newGame);

        // add the new game to every online lobby user's lobby
        Iterator<User> userIterator = Context.onlineUsers.iterator();
        User otherUser;
        while (userIterator.hasNext()) {
            otherUser = userIterator.next();
//            if (otherUser.inLobby && getId(otherUser) != id) {
            if (otherUser.inLobby) {
                try {
                    otherUser.newOpenGames.put(newGame);
                } catch (InterruptedException e) {
                        System.out.println("NewGameServlet exception: " + e.getMessage());
                    }
            }
        }
        System.out.println("NewGameServlet post: finished");
    }
    
//    private int getId(User user) {
//        for (int i = 0; i < Context.users.length; i++) {
//            if (Context.users[i] == user) {
//                return i;
//            }
//        }
//        return -1;
//    }

}
